<?php
namespace ac\modules\control\controllers;

use Yii;
use ac\controllers\AuthController;
use app\models\AdminRole;
use app\models\AdminRolePriv;
use app\modules\developer\models\Menu;
use common\component\exception\ErrMap;
use common\component\tool\Tool;
use common\models\OperationLog;


class AdminRoleController extends AuthController
{

	/*角色列表*/
    public function actionAdminRoleList()
    {
        $where = '';
        if(isset($this->get['display']) and $this->get['display'] == 2){
            $where = 'display = 2 and ';
        }
        $adminRoleList = [];
        if(($comid = $this->checkComID( $this->userInfo['comid'] )) !== false){
            $adminRoleList = AdminRole::find()->where($where . 'comid = :comid', [':comid' => $comid])->asArray()->all();
        }
        return Tool::showRes([0, '获取成功'], $adminRoleList);
    }

    /*添加角色*/
    public function actionAddAdminRole()
    {
        if(Yii::$app->request->isPost and
            $this->checkComID( $this->userInfo['comid'] )){
            $adminRole = new AdminRole;
            if($adminRole->addAdminRole($this->post)){
                $backInfo = [0, '添加角色成功'];//返回信息
            }else{
                if($adminRole->hasErrors()){
                    $backInfo = ErrMap::getError(10005);//返回信息
                    $exception = $adminRole->getErrors();//异常信息
                    if(array_key_exists("repeatRolename", $exception)){
                        $backInfo = ErrMap::getError(10005, '此名称已存在');//返回信息
                    };
                }
            }
        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }

    /*
    修改角色
    */
    public function actionModifyAdminRole()
    {
        /*取出单个数据*/
        if(Yii::$app->request->isGet){
            $id = isset($this->get['id'])?$this->get['id']:'';
            if($id){
                $adminRole = AdminRole::find()->where('role_id = :id', [':id' => $id])->asArray()->one();
                if(!is_null($adminRole) and $this->checkComID($adminRole['comid'])){
                    return Tool::showRes([0, '获取成功'], $adminRole);
                }else{
                    return Tool::showRes(ErrMap::getError(10010));
                };
            }
        }

        /*如果有数据，进行修改*/
        if(Yii::$app->request->isPost and
            $this->checkComID( $this->userInfo['comid'] )){
            $id = isset($this->post['AdminRole']['id'])?intval($this->post['AdminRole']['id']):'';
            if(!$id){
                $backInfo = ErrMap::getError(10005);//返回信息
            }else{
                $adminRole = new AdminRole;
                if($adminRole->modifyAdminRole($this->post, $id)){
                    $backInfo = [0, '修改角色成功'];//返回信息
                }else{
                    if($adminRole->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $adminRole->getErrors();//异常信息
                        if(array_key_exists("repeatRolename", $exception)){
                            $backInfo = ErrMap::getError(10005, '此名称已存在');//返回信息
                        };
                    }
                }
            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }

        return Tool::showRes(ErrMap::getError(10005));
    }

    /*排序*/
    public function actionSetSort()
    {
        if(Yii::$app->request->isPost){
            $sort = $this->post['sort'];
            // P($sort);
            if(!empty($sort) and is_array($sort)){
                $adminRole = new AdminRole;
                if($adminRole->setSort($sort)){
                    $backInfo = [0, '设置排序成功'];//返回信息
                }else{
                    if($adminRole->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $adminRole->getErrors();//异常信息
                    }
                }
            }
            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*删除角色,（真删除）*/
    public function actionDeleteAdminRole()
    {
        $id = isset($this->post['id'])?$this->post['id']:'';
        if($id and $this->checkComID( $this->userInfo['comid'] )){
            $adminRole = new AdminRole;
            //*******注意，这里需要完善，同时删除所有该角色的权限
            if($adminRole->deleteAll('role_id = :id', [':id' => $id])){//删除成功
                $backInfo = [0, '删除角色成功'];//返回信息
            }else{//删除失败
                $backInfo = ErrMap::getError(10013, '删除角色失败');//返回信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), '') ) != 'boolean'){
                return $res;
            };

        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*设置权限*/
    public function actionSetPermissions()
    {
        // P($this->permissions);
        // echo $this->get['appid'];
        /*取出权限*/
        if(Yii::$app->request->isGet and
            isset($this->get['role_id']) and
            isset($this->get['appid'])){
            $adminRolePriv = AdminRolePriv::find()
                                ->select(['mid', 'm', 'c', 'a', 'half'])
                                ->where('role_id = :id and (appid = :appid or appid = "")', [':id' => $this->get['role_id'], ':appid' => $this->get['appid']])
                                // ->createCommand()->getRawSql();
                                ->asArray()->all();
            // P($adminRolePriv);
            return Tool::showRes([0, '获取成功'], $adminRolePriv);
        }
        if(Yii::$app->request->isPost and
            $this->checkComID( $this->userInfo['comid'] ) and
            isset($this->post['role_id']) and
            isset($this->post['appid']) and
            isset($this->post['data'])){
            // P($this->post['data']);
            if(count($this->post['data']) > 0){
                /*收集ID*/
                $ids = [];
                foreach($this->post['data'] as $k => $v){
                    array_push($ids, $k);
                }
                // P($this->post['data']);

                $menu = Menu::find()->select(['id', 'app_info_id', 'apikeyname', 'm', 'c', 'a', 'args'])
                        ->where(['in', 'id', $ids])
                        ->asArray()->all();
                // P($menu);

                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    $adminRolePriv = new AdminRolePriv;
                    if($adminRolePriv->deleteAll('role_id = :id and (appid = :appid or appid = "")', [':id' => $this->post['role_id'], ':appid' => $this->post['appid']]) < 0){
                        $pass = false;
                        $backInfo = ErrMap::getError(10013);//删除失败
                    }
                    foreach($menu as $k => $v){
                        $adminRolePriv = new AdminRolePriv;
                        if($v['app_info_id'] == 0){
                            $appid = '';
                        }else{
                            $appid = $this->post['appid'];
                        }
                        $data = array(
                            'AdminRolePriv' => array(
                                'role_id' => $this->post['role_id'],
                                'appid' => $appid,
                                'mid' => $v['id'],
                                'apikeyname' => $v['apikeyname'],
                                'm' => $v['m'],
                                'c' => $v['c'],
                                'a' => $v['a'],
                                'half' => $this->post['data'][$v['id']],
                            )
                        );
                        // P($data, false);
                        if(!$adminRolePriv->addRolePriv($data)){
                            $pass = false;
                            if($adminRolePriv->hasErrors()){
                                $backInfo = ErrMap::getError(10005);//返回信息
                                $exception = $adminRolePriv->getErrors();//异常信息
                            }
                        }
                    }

                    if($pass){
                        $backInfo = [0, '权限设置成功'];//返回信息
                        $transaction->commit();
                    }
                }catch(\Exception $exception){
                    $transaction->rollback();       
                };

                if(!isset($backInfo)){
                    $backInfo = ErrMap::getError(10005);//返回信息
                }
                if(!isset($exception)){
                    $exception = '';//异常信息
                }
                // P($exception);
                //操作日志
                if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception) ) != 'boolean'){
                    return $res;
                };
            }
        }
    }

}